/*
 * catalog.c
 *
 *  Import function:
 *            int loadcatalog(*char filename, **double data, *int numberEvents)
 *
 *  catalog in ZMAP format:
 *       1. Longitude [deg]
 *       2. Latitude [deg]
 *       3. Decimal year (e.g., 2005.5 for July 1st, 2005)
 *       4. Month
 *       5. Day
 *       6. Magnitude
 *       7. Depth [km]
 *       8. Hour
 *       9. Minute
 *      10. Second
 *      11. Horizontal error
 *      12. Depth error
 *      13. Magnitude error
 *      14. Name of seismic network (this field is not used by the CSEP, it's a legacy data field from the RELM experiment)
 *
 *
 *
 *  Created on: Jun 28, 2013
 *      Author: cbach
 */

#include <stdio.h>
#include <stdlib.h>
#include "catalog.h"
#include "nrutil.h"


// reads catalog, allocates memory to data, returns number of lines
int catalogRead(char *filename, double ***data) {

    FILE *fin;
    int i, numberLines;
    char cdum[1025];

    /**************************************************************************/
    // open file
    if ((fin = fopen(filename, "r")) == NULL) {
        fprintf(stderr, "ERROR in catalogRead: \nCannot open file %s!\n", filename);
        return(-1);
    }
    /**************************************************************************/
    // count number of lines having more than one character
    // this is done to exclude clear lines at the file end
    numberLines = 0;
    while (fgets(cdum, 1024, fin) != NULL)
        numberLines++;
    /**************************************************************************/
    // allocate memory for catalog data matrix
    *data = dmatrix(1, numberLines, 1, 14);
    /**************************************************************************/
    // set file pointer back to begin of file
    rewind(fin);
    /**************************************************************************/
    // read data[row][column] --> 14 columns
    for (i=1; i<=numberLines; i++) {
        // get current line
        if (fgets(cdum, 1024, fin) != NULL) {
            // read 14 doubles from current line
            if (sscanf(cdum, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf",
                    &(*data)[i][1], &(*data)[i][2], &(*data)[i][3], &(*data)[i][4], &(*data)[i][5],
                    &(*data)[i][6], &(*data)[i][7], &(*data)[i][8], &(*data)[i][9], &(*data)[i][10],
                    &(*data)[i][11], &(*data)[i][12], &(*data)[i][13], &(*data)[i][14]) != 14) {
                fprintf(stderr, "ERROR in catalogRead: error reading data using sscanf()\n");
                return(-2);
            }

        }
        else {
            fprintf(stderr, "ERROR in catalogRead: error reading data using fgets()\n");
            return(-3);
        }
    }


    fclose(fin);

    return(numberLines);
}



int catalogFree(double ***catalog, int numberLines) {

    free_dmatrix(*catalog, 1, numberLines, 1, 14);

    return(0);

}
